<template>
    <div class="vanishGameContent">
        <div class="game-info">
            <div class="game-info-text">分数: <span>{{ score }}</span></div>
            <div class="game-info-text">剩余时间: <span>{{ timeLeft }}</span> 秒</div>
            <button @click="startGame" v-if="!gameStarted">开始游戏</button>
            <button @click="resetGame" v-else>重新开始</button>
        </div>
        <div class="game-board">
            <div v-for="(tile, index) in tiles" :key="index" class="tile" :class="{
                [tile.color]: true,
                selected: tile.selected,
                'can-remove': tile.canRemove
            }" @click="selectTile(index)"></div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast, showFailToast, showConfirmDialog } from 'vant'


const route = useRoute()
const router = useRouter()

// 游戏配置
const config = {
    rows: 8,
    cols: 8,
    colors: ['red', 'blue', 'green', 'yellow', 'purple'],
    gameTime: 60 // 游戏时长(秒)
}

// 游戏状态
const tiles = ref<any>([])
const score = ref(0)
const timeLeft = ref<number>(config.gameTime)
const gameStarted = ref<boolean>(false)
const selectedTileIndex = ref(null)
const timer = ref<any>(null)

// 初始化游戏板
const initializeBoard = () => {
    tiles.value = Array.from({ length: config.rows * config.cols }, () => ({
        color: config.colors[Math.floor(Math.random() * config.colors.length)],
        selected: false,
        canRemove: false
    }))

    // 确保初始状态没有可消除的组合
    while (checkMatches().length > 0) {
        initializeBoard()
    }
}

// 检查是否有匹配项
const checkMatches = () => {
    const matches = []
    const board = tiles.value

    // 检查水平匹配
    for (let row = 0; row < config.rows; row++) {
        for (let col = 0; col < config.cols - 2; col++) {
            const index = row * config.cols + col
            if (board[index].color === board[index + 1].color &&
                board[index].color === board[index + 2].color) {
                matches.push(index, index + 1, index + 2)
            }
        }
    }

    // 检查垂直匹配
    for (let col = 0; col < config.cols; col++) {
        for (let row = 0; row < config.rows - 2; row++) {
            const index = row * config.cols + col
            if (board[index].color === board[index + config.cols].color &&
                board[index].color === board[index + 2 * config.cols].color) {
                matches.push(index, index + config.cols, index + 2 * config.cols)
            }
        }
    }

    return [...new Set(matches)] // 去重
}

// 高亮显示可消除的方块
const highlightRemovableTiles = () => {
    // 重置所有canRemove状态
    tiles.value.forEach(tile => {
        tile.canRemove = false
    })

    const matches = checkMatches()
    matches.forEach(index => {
        tiles.value[index].canRemove = true
    })
}

// 选择方块
const selectTile = (index: any) => {
    if (!gameStarted.value) {
        showToast('游戏尚未开始')
        return
    }
    // 如果已经选择了一个方块
    if (selectedTileIndex.value !== null) {
        // 如果点击的是同一个方块，取消选择
        if (selectedTileIndex.value === index) {
            tiles.value[index].selected = false
            selectedTileIndex.value = null
            return
        }
        // 尝试交换
        swapTiles(selectedTileIndex.value, index)

        // 取消选择
        tiles.value[selectedTileIndex.value].selected = false
        selectedTileIndex.value = null
    } else {
        // 选择新方块
        tiles.value[index].selected = true
        selectedTileIndex.value = index
    }
}

// 交换两个方块
const swapTiles = (index1, index2) => {
    // 检查是否相邻
    const row1 = Math.floor(index1 / config.cols)
    const col1 = index1 % config.cols
    const row2 = Math.floor(index2 / config.cols)
    const col2 = index2 % config.cols

    const isAdjacent =
        (Math.abs(row1 - row2) === 1 && col1 === col2) ||
        (Math.abs(col1 - col2) === 1 && row1 === row2)

    if (!isAdjacent) return false

    // 交换颜色
    const tempColor = tiles.value[index1].color
    tiles.value[index1].color = tiles.value[index2].color
    tiles.value[index2].color = tempColor
    // 检查是否有匹配
    const matches = checkMatches()
    if (matches.length > 0) {
        removeMatches(matches)
        return true
    } else {
        // 如果没有匹配，交换回来
        const tempColor = tiles.value[index1].color
        tiles.value[index1].color = tiles.value[index2].color
        tiles.value[index2].color = tempColor
        return false
    }
}
// 移除匹配的方块
const removeMatches = (matches) => {
    // 增加分数
    score.value += matches.length * 10

    // 移除匹配的方块
    matches.forEach(index => {
        tiles.value[index].color = null
    })

    // 下落方块
    dropTiles()

    // 填充新的方块
    fillEmptyTiles()
    // 检查是否有新的匹配
    setTimeout(() => {
        const newMatches = checkMatches()
        if (newMatches.length > 0) {
            removeMatches(newMatches)
        } else {
            highlightRemovableTiles()
        }
    }, 300)
}

// 方块下落
const dropTiles = () => {
    for (let col = 0; col < config.cols; col++) {
        let emptyRow = config.rows - 1

        for (let row = config.rows - 1; row >= 0; row--) {
            const index = row * config.cols + col
            if (tiles.value[index].color !== null) {
                if (row !== emptyRow) {
                    const emptyIndex = emptyRow * config.cols + col
                    tiles.value[emptyIndex].color = tiles.value[index].color
                    tiles.value[index].color = null
                }
                emptyRow--
            }
        }
    }
}
// 填充空方块
const fillEmptyTiles = () => {
    for (let col = 0; col < config.cols; col++) {
        for (let row = 0; row < config.rows; row++) {
            const index = row * config.cols + col
            if (tiles.value[index].color === null) {
                tiles.value[index].color = config.colors[Math.floor(Math.random() * config.colors.length)]
            }
        }
    }
}
// 开始游戏
const startGame = () => {
    score.value = 0
    timeLeft.value = config.gameTime
    gameStarted.value = true
    initializeBoard()
    highlightRemovableTiles()

    // 开始计时
    timer.value = setInterval(() => {
        timeLeft.value--
        if (timeLeft.value <= 0) {
            clearInterval(timer.value)
            gameStarted.value = false
            showConfirmDialog({
                title: '',
                message: `游戏结束! 你的得分是: ${score.value}`,
            }).then(() => {
                resetGame()
            })
            .catch(() => {
                // on cancel
                router.back()
            })
        }
    }, 1000)
}
// 重置游戏
const resetGame = () => {
    clearInterval(timer.value)
    startGame()
}

// 初始化
onMounted(() => {
    initializeBoard()
    highlightRemovableTiles()
})

onUnmounted(() => {
    if (timer.value) {
        clearInterval(timer.value)
    }
})

</script>


<style lang="scss" scoped>
.vanishGameContent {
    width: 100%;
    height: auto;
    position: relative;
    padding: 15px;
    text-align: center;
    font-family: Arial, sans-serif;
    .game-info {
        margin: 20px 0;
        display: flex;
        justify-content: space-around;
        align-items: center;
        .game-info-text {
            font-size: 16px;
            font-weight: 500;
            span {
                font-size: 22px;
                font-weight: 500;
                color: #aa46bb;
            }
        }
    }
    .game-board {
        display: grid;
        grid-template-columns: repeat(8, 1fr);
        gap: 5px;
        margin: 0 auto;
        width: 100%;
        aspect-ratio: 1 / 1;
        height: auto;
    }
    .tile {
        width: 100%;
        height: 100%;
        border-radius: 8px;
        cursor: pointer;
        transition: all 0.3s ease;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
    }
    .tile.selected {
        transform: scale(0.9);
        box-shadow: 0 0 10px 3px rgba(255, 255, 255, 0.7);
    }
    .tile.can-remove {
        animation: pulse 1s infinite;
    }
    @keyframes pulse {
        0% {
            transform: scale(1);
        }
        50% {
            transform: scale(1.1);
        }
        100% {
            transform: scale(1);
        }
    }
    /* 颜色类 */
    .red {
        background-color: #ff5252;
    }
    .blue {
        background-color: #4285f4;
    }
    .green {
        background-color: #0f9d58;
    }
    .yellow {
        background-color: #ffbc00;
    }
    .purple {
        background-color: #aa46bb;
    }
    button {
        padding: 8px 16px;
        background-color: #4285f4;
        color: white;
        border: none;
        border-radius: 8px;
        cursor: pointer;
        font-size: 16px;
    }
    button:hover {
        background-color: #3367d6;
    }
}
</style>